import {getCurrentInstance} from "./component";

export function provide(key, value) {
    const currentInstance: any = getCurrentInstance()
    if (currentInstance) {
        let {provides} = currentInstance;
        const parentProvides = currentInstance.parent.provides
        //  如果在一个setup函数内调用两次 provide函数,后一次会把前一次的结果覆盖掉,所以只能做一次初始化.
        if (provides == parentProvides) {
            //  设置当前实例的原型链 是父组件的 provide
            provides = currentInstance.provides = Object.create(parentProvides);
        }
        provides[key] = value
    }

}

export function inject(key, defaultValue) {
    // 获取到当前运行实例
    const currentInstance: any = getCurrentInstance();
    if (currentInstance) {
        const parentProvide = currentInstance.parent.provides
        if (key in parentProvide) {
            return parentProvide[key]
        } else if (defaultValue) {
            if (typeof defaultValue === 'function') {
                return defaultValue();
            }
            return defaultValue;
        }
    }
}
